package com.anlogic.sdk.programflash.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;

import com.anlogic.sdk.programflash.ProgramFlashModel;
import com.anlogic.sdk.programflash.ui.ProgramFlashDialog;
import com.anlogic.sdk.programflash.utils.ProgramFlashUtils;
import com.anlogic.sdk.utils.EnvUtils;
import com.anlogic.sdk.utils.UIUtils;

public class ProgramFlashHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
		ProgramFlashDialog dialog = new ProgramFlashDialog(window.getShell());
		int ret = dialog.open();
		if (ret == ProgramFlashDialog.OK) {
			run(dialog.getModel());
		}
		return null;
	}
	
	public void run(ProgramFlashModel model) {
		ProgramFlashUtils.writeScript(model);
		if (model.isLocal()) {
			if (!EnvUtils.checkOpenocd()) {
				UIUtils.showMessageDialog("ProgramFlash", "OpenOCD not found! Please check your environment!", MessageDialog.ERROR);
				return;
			}
			ProgramFlashUtils.programFlashWithServer(model);
		} else {
			ProgramFlashUtils.programFlash(model);
		}
	}
}
